import {
	GridActionType,
	ICtrlDataAction,
	ICtrlEvent,
	IGridAbility,
	IGridControllerParams,
	IGridModel,
	IGridStore,
	IParam,
} from '@/core';
import { QXEvent } from 'qx-util';
import { PropType } from 'vue';
import {
	getCtrlClassNames,
	handlePageChange,
	handlePageSizeChange,
	handleSortChange,
	useCtrlAction,
	useCtrlBasic,
	useCtrlControllerParams,
	useCtrlProps,
} from '../use-ctrl';

/**
 * 表格输入参数
 *
 * @export
 * @return {*}
 */
export function useGridProps() {
	return {
		...useCtrlProps(),
		openView: Function,
		newView: Function,
		actions: Object as PropType<ICtrlDataAction>,
		selectFirstDefault: Boolean,
		rowActiveMode: {
			type: Number as PropType<0 | 1 | 2>,
			default: 2,
		},
		defaultEnableRowEdit: Boolean,
		autoLoad: {
			type: Boolean,
			default: false,
		},
		localMode: {
			type: Boolean,
			default: false,
		},
		singleSelect: {
			type: Boolean,
			default: false,
		},
	};
}

/**
 * 表格基础参数
 *
 * @export
 * @param {IGridModel} model
 * @param {IParam} props
 * @return {*}
 */
export function useGridBasic(model: IGridModel, props: IParam) {
	const getClassNames = (props: IParam) => {
		const names = getCtrlClassNames(model, props);
		Object.assign(names, {
			'app-control-grid--no-paging-bar': model.enablePagingBar,
		});
		return names;
	};
	return {
		...useCtrlBasic(model, props),
		getClassNames,
		slotKeys: Object.keys(useSlots()),
		handlePageChange,
		handlePageSizeChange,
		handleSortChange,
	};
}

/**
 * 表格部件行为
 *
 * @export
 */
export function useGridAction(controller: any) {
	const handleRowClick = (row: IParam, event: MouseEvent) => {
		controller.rowClick(row, event);
	};

	const handleFilterChange = ($event: IParam) => {
		controller.handleFilterChange($event);
	};
	const handleRowDbClick = (row: IParam, event: MouseEvent) => {
		controller.rowDbClick(row, event);
	};

	const handleSelectionChange = (selections: IParam[]) => {
		controller.selectionChange(selections);
	};

	const handleCustomCallBack = () => {
		return controller.customCallBack();
	};
	const handleRemove = ($event: IParam[]) => {
		return controller.remove($event);
	};
	return {
		...useCtrlAction(controller),
		handleRowClick,
		handleFilterChange,
		handleRowDbClick,
		handleSelectionChange,
		handleCustomCallBack,
		handleRemove,
	};
}

/**
 * 表格部件控制器
 *
 * @export
 */
export function useGridControllerParams<
	S extends IGridStore,
	M extends IGridModel
>(
	model: M,
	props: any,
	evt: QXEvent<ICtrlEvent<GridActionType, IGridAbility>>,
    otherParams: IParam = {},
): IGridControllerParams<GridActionType, IGridAbility> {
	return {
		...useCtrlControllerParams<S, M>(model, props, evt, otherParams),
		autoLoad: props.autoLoad,
		defaultEnableRowEdit: props.defaultEnableRowEdit,
		actions: props.actions,
		rowActiveMode: props.rowActiveMode,
		singleSelect: props.singleSelect,
		selectFirstDefault: props.selectFirstDefault,
		openView: props.openView,
		newView: props.newView,
	};
}
